/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package accountManagement.sessionbean;

import javax.ejb.LocalBean;
import accountManagement.entity.Employee;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 *
 * @author Wei Haoyang
 */
@Stateless
@LocalBean
public class EmployeeManager {

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    @PersistenceContext
    private EntityManager em;
    private Employee employee;
    
    public Employee getEmployeeById(Long EmployeeId)
    {
        return em.find(Employee.class, EmployeeId);
    }
    
    public void resetPassword(Employee employeeTemp ){
        
        employee=employeeTemp;
        em.merge(employee);
    }
    
    
    public List<Employee> getEmployeeByName(String userName)
    {
        Query query = em.createQuery("SELECT u FROM Employee u WHERE u.name = :inUserName");
        query.setParameter("inUserName", userName);
        List<Employee> employee = null;
        try{
            employee = query.getResultList();
        }
        catch(NoResultException ex){
            ex.printStackTrace();
        }
        return employee;
    }
    
    public void addEmployee (Employee employee) throws Exception
    {
        try{
        em.persist(employee);
        }
        catch (Exception e){
            throw e;
        }
    }
    
    public void editEmployee(Employee employee)
    {
        em.merge(employee);
    }
    

    public void removeEmployee(Long EmployeeId)
    {
        Employee employee = em.find(Employee.class, EmployeeId);
        em.remove(employee);
    }
    
    public List<Employee> getAllEmployees() throws NoResultException{
        Query query = em.createQuery("SELECT s1 FROM Employee s1");
        return query.getResultList();
    }
    
    public Employee getEmployeeByUserName(String uName){
        Query query = em.createQuery("SELECT u FROM Employee u WHERE u.userName = :inUserName");
        query.setParameter("inUserName", uName);
        Employee employee = null;
        try{
            employee = (Employee)query.getSingleResult();
        }
        catch(NoResultException ex){
            throw ex;
        }
        return employee;
    }

    public Employee getEmployee() {
        return employee;
    }

    public void setEmployee(Employee employee) {
        this.employee = employee;
    }
   

}
